/*Copyright (c) Microsoft Open Technologies, Inc.  All rights reserved.
Microsoft Open Technologies would like to thank its contributors, a list
of whom are at https://interview.codeplex.com/team/views.

Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing permissions
and limitations under the License.*/

// Problem:
//     There are many cups and each of them can contains c L wine, and the cups are put as pyramid
//     1
//    2 3
//   4 5 6
//  7 8 9 10
//     When one cup is full, the wine will flow to the cups under it.
//     e.g. if 1 cup is full, the rest wine will flow to 2 & 3 uniformly; if 2 is full, wine will flow to 4&5
//
// Question: please tell me how much wine in nth cup if giving N L wine

#include <map>
#include <iostream>
using namespace std;

template<int, int>
float get_unlimited_wine_amount(int x, int y);

map<int, float> val;

template<int N, int c>
float get_wine_amount(int n) {
    float ret = 0, x, y;

    for (x = 1; ;x++) {
        if (((x + 1) * x)/2 >= n)
            break;
    }

    y = n - ((x - 1) * x)/2;

    ret = get_unlimited_wine_amount<N, c>(x, y);
    val.insert(make_pair(n, ret));

    return ret > c ? c : ret;
}

template<int N, int c>
float get_unlimited_wine_amount(int x, int y) {
    if (x == 1 && y == 1) {
        return N;
    }

    float ret = 0;
    if (y == 1 || y == x) {
        ret = 1.0 * (get_unlimited_wine_amount<N, c>(x-1, 1) -c ) /2;
        return ret > 0 ? ret : 0;
    }

    float left = get_unlimited_wine_amount<N, c>(x-1, y-1) - c;
    left = left > 0 ? left : 0;
    float right = get_unlimited_wine_amount<N, c>(x-1, y) - c;
    right = right > 0 ? right : 0;
    ret = (left + right) / 2;
    return ret > 0 ? ret : 0;
}

int main(int argc, char* argv[]) {
    for (int i=1; i<20; i++) {
        cout << i << " = " << get_wine_amount<20, 2>(i) << endl;
    }

    for (auto a : val) {
	cout << a.first << " = " << a.second << endl;
    }
    return 0;
}
